<template>
  <div class="list-container">
    <div>
      <div class="handle-box">
        <el-select v-model="pagination.userType" placeholder="用户类型" class="handle-select mr-2">
          <el-option key="1" label="Boss" :value="0"></el-option>
          <el-option key="2" label="管理员" :value="1"></el-option>
          <el-option key="3" label="普通用户" :value="2"></el-option>
        </el-select>
        <el-select v-model="pagination.userStatus" placeholder="用户状态" class="handle-select mr-2">
          <el-option key="1" label="启用" :value="true"></el-option>
          <el-option key="2" label="禁用" :value="false"></el-option>
        </el-select>
        <el-input v-model="pagination.keywords" placeholder="用户名/手机号" class="handle-input mr-2"></el-input>
        <el-button type="primary" @click="searchUser()" class="mr-2">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button type="danger" @click="clearSearch()">清除参数</el-button>
      </div>
      <el-table :data="users" border class="table" header-cell-class-name="table-header">
        <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column label="用户状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.userStatus === false ? 'danger' : 'success'"
                    disable-transitions>
              {{scope.row.userStatus === false ? '禁用' : '启用'}}
            </el-tag>
            <el-switch @click="changeUserStatus(scope.row)" v-model="scope.row.userStatus"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center">
          <template #default="scope">
            <el-image class="table-td-thumb" :src="scope.row.avatar" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <el-tag type="success"
                    v-if="scope.row.gender === 1"
                    disable-transitions>
              男
            </el-tag>
            <el-tag type="success"
                    v-else-if="scope.row.gender === 2"
                    disable-transitions>
              女
            </el-tag>
            <el-tag type="success"
                    v-else
                    disable-transitions>
              保密
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="introduction" label="简介" align="center"></el-table-column>
        <el-table-column label="用户类型" width="100" align="center">
          <template #default="scope">
            <el-tag type="success"
                    v-if="scope.row.userType === 0"
                    style="cursor: pointer"
                    @click="editUser(scope.row)"
                    disable-transitions>
              Boss
            </el-tag>
            <el-tag type="success"
                    v-else-if="scope.row.userType === 1"
                    style="cursor: pointer"
                    @click="editUser(scope.row)"
                    disable-transitions>
              管理员
            </el-tag>
            <el-tag type="success"
                    v-else
                    style="cursor: pointer"
                    @click="editUser(scope.row)"
                    disable-transitions>
              普通用户
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" align="center"></el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next"
                       :current-page="pagination.current"
                       :page-size="pagination.size"
                       :total="pagination.total"
                       @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="修改用户类型"
               v-model="editVisible"
               width="30%"
               :before-close="handleClose"
               :append-to-body="true"
               destroy-on-close
               center>
      <div class="flex justify-center">
        <el-radio-group v-model="changeUser.userType">
          <el-radio-button :label="0">Boss</el-radio-button>
          <el-radio-button :label="1">管理员</el-radio-button>
          <el-radio-button :label="2">普通用户</el-radio-button>
        </el-radio-group>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button type="primary" @click="saveEdit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import api from '../../utils/api';

// 注入依赖
const common = inject('$common');

// 响应式状态
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  keywords: "",
  userStatus: null,
  userType: null
});
const users = ref([]);
const changeUser = reactive({
  id: null,
  userType: null
});
const editVisible = ref(false);

// 生命周期钩子
onMounted(() => {
  getUsers();
});

// 方法
const clearSearch = () => {
  pagination.current = 1;
  pagination.size = 10;
  pagination.total = 0;
  pagination.keywords = "";
  pagination.userStatus = null;
  pagination.userType = null;
  getUsers();
};

const getUsers = () => {
  api.user.getList(pagination)
    .then((res) => {
      if (!common.isEmpty(res.data)) {
        users.value = res.data.records;
        pagination.total = res.data.total;
      }
    })
    .catch((error) => {
      ElMessage.error(error.message);
    });
};

const changeUserStatus = (user) => {
  const originalStatus = user.userStatus;
  
  ElMessageBox.confirm(`确认${user.userStatus ? '启用' : '禁用'}该用户？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    api.user.changeStatus({
      userId: user.id,
      flag: user.userStatus
    })
      .then(() => {
        ElMessage.success("修改成功！");
      })
      .catch((error) => {
        user.userStatus = originalStatus;
        ElMessage.error(error.message);
      });
  }).catch(() => {
    user.userStatus = originalStatus;
    ElMessage.info('已取消操作');
  });
};

const editUser = (user) => {
  changeUser.id = user.id;
  changeUser.userType = user.userType;
  editVisible.value = true;
};

const saveEdit = () => {
  ElMessageBox.confirm('确认修改用户类型？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    api.user.changeType(changeUser)
      .then(() => {
        ElMessage.success("修改成功！");
        getUsers();
        handleClose();
      })
      .catch((error) => {
        ElMessage.error(error.message);
      });
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

const searchUser = () => {
  pagination.current = 1;
  getUsers();
};

const handlePageChange = (val) => {
  pagination.current = val;
  getUsers();
};

const handleClose = () => {
  editVisible.value = false;
};
</script>

<style scoped>
.list-container {
  padding: 20px;
}

.handle-box {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.handle-input {
  width: 180px;
}

.handle-select {
  width: 140px;
}

.table {
  width: 100%;
  margin-bottom: 20px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.mr-2 {
  margin-right: 10px;
}
</style>
